package module4.homework;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {

    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket s1 = null;
        PrintStream ps = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {
            //1、创建ServerSocket类型的对象并提供端口
            ss = new ServerSocket(8887);
            //2、等待客户端的链接请求，调用accept方法
            System.out.println("等待客户端的链接请求...");
            s1 = ss.accept();
            System.out.println("客户端链接成功！");
            //3、使用输入输出流进行通信
            //实现对客户端发来的字符串内容的接收并打印
            ps = new PrintStream(s1.getOutputStream());
            ps.println("你好，请输入你的账户和密码：");
            oos = new ObjectOutputStream(s1.getOutputStream());
            ois = new ObjectInputStream(s1.getInputStream());
            UserMessage um1 = new UserMessage("check", new User("admin", "123456"));

            boolean flag = true;
            while (flag) {
                //读取传入的账户密码
                Object obj = ois.readObject();
                System.out.println("读取成功！");
                if (((UserMessage) obj).equals(um1)) {
                    ((UserMessage) obj).setType("success");
                    flag = false;
                } else {
                    ((UserMessage) obj).setType("fail");
                }
                oos.writeObject(obj);
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            //4、关闭Socket并释放相关的资源
            if (null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != s1) {
                try {
                    s1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ss) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
